/** 6. SQL生成与执行 */
<template>
  <div class="editor_container">
    <div class="code-container">
      <div class="code-header">
        <h4>SQL 生成</h4>
        <a-space
          size="middle"
          style="
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            gap: 8px;
          "
        >
          <a-button
            :disabled="!excel_href"
            @click="download_file('DataGrid', excel_href)"
            :loading="uploading"
          >
            <DownloadOutlined />
            下载 Excel
          </a-button>
          <a-upload
            name="file"
            :file-list="excel_file_list"
            :before-upload="before_upload"
            :maxCount="1"
            :show-upload-list="false"
          >
            <a-button :disabled="uploading || is_finished">
              <UploadOutlined />
              上传 Excel
            </a-button>
          </a-upload>
          <a-button
            @click="generate_sql"
            type="primary"
            :disabled="is_finished"
          >
            <RocketOutlined />
            生成 SQL
          </a-button>
        </a-space>
      </div>
      <MonacoEditor editorId="sqlGenerationEditor" v-model="script_code" />
    </div>
    <div class="result-container">
      <div class="result-header">
        <h4>执行结果</h4>
        <a-space
          size="middle"
          style="
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            gap: 8px;
          "
        >
          <a-button
            v-show="!is_finished"
            :disabled="script_code === '等待生成...'"
            @click="execute_sql"
            type="primary"
          >
            <RocketOutlined />
            执行 SQL
          </a-button>
          <a-button
            @click="sync_category"
            type="primary"
            v-show="ready_to_sync"
          >
            <FileSyncOutlined />
            同步类目
          </a-button>
          <a-button v-show="is_finished" @click="finish" type="primary">
            <CheckOutlined />
            完成
          </a-button>
        </a-space>
      </div>
      <MonacoEditor
        editorId="sqlGenerationResultEditor"
        v-model="result_code"
        :readOnly="true"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, createVNode } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { script_execute } from '@/api/script';
import {
  fetch_process_data,
  excel_generate,
  sql_generate,
  sql_execute,
  sync_align_result,
} from '@/utils/selection.js';
import { uploadFile } from '@/api/global.js';
import { useRouter } from 'vue-router';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

const emit = defineEmits(['finish']);
const $router = useRouter();

// 获取当前进度数据
const process_data = ref({});

// 步骤数据
const step_data = ref({
  read_only: false,
  tear_conditions: [],
});

const script_code = ref('等待生成...');
const result_code = ref('等待执行...');

const excel_href = ref('');
const excel_file_list = ref([]);
const uploading = ref(false);
const is_finished = ref(false);
const ready_to_sync = ref(false);

onMounted(async () => {
  // 获取当前进度数据
  message.info('正在获取对齐进度数据...');
  process_data.value = await fetch_process_data();

  // 生成数据表格
  message.info('正在生成数据表格...');
  try {
    const excel_res = await excel_generate(process_data.value);
    console.log('excel_res ->', excel_res);
    excel_href.value = JSON.parse(excel_res.data);
    if (excel_href.value) {
      message.success('生成数据表格成功');
    } else {
      message.error('生成数据表格失败: 结果为空');
    }
  } catch (err) {
    message.error('生成数据表格失败');
    console.error('generate excel error ->', err);
  }
});

// 下载文件
const download_file = (prefix, file_url) => {
  // 生成文件名 ${prefix}_2021-08-11_16-00-00.xlsx
  let file_name = `${prefix}_${new Date().toLocaleDateString()}_${new Date().toLocaleTimeString()}.xlsx`;
  let a = document.createElement('a');
  a.href = file_url;
  a.download = file_name;
  a.click();
};

// 处理文件上传
const before_upload = async file => {
  Modal.confirm({
    title: '是否上传替代当前 Excel ？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '上传后将替代当前 Excel 文件参与 SQL 生成, 请确保上传的 Excel 文件格式与内容正确!'
    ),
    async onOk() {
      uploading.value = true;
      excel_file_list.value = [...(excel_file_list.value || []), file];
      console.log('excel_file_list ->', excel_file_list.value);

      // 上传文件
      try {
        const upload_res = await uploadFile(file, 'CategoryExcel');
        console.log('upload_res ->', upload_res);
        excel_href.value = upload_res.data;
        message.success('上传成功');
      } catch (err) {
        message.error('上传文件时发生错误');
        console.error('upload file error ->', err);
      }
      uploading.value = false;
    },
    onCancel() {
      console.log('Modal Canceled');
    },
    class: 'test',
  });
  return false;
};

// 生成 SQL
const generate_sql = async () => {
  try {
    const sql_generate_res = await sql_generate(excel_href.value);
    console.log('sql_generate_res ->', sql_generate_res);
    script_code.value = JSON.parse(sql_generate_res.data);
  } catch (err) {
    message.error('生成 SQL 时发生错误');
    console.error('generate sql error ->', err);
  }
};

// 执行 SQL
const execute_sql = async () => {
  try {
    const sql_execute_res = await sql_execute(script_code.value);
    console.log('sql_execute_res ->', sql_execute_res);
    result_code.value = sql_execute_res.data;
    is_finished.value = true;
    ready_to_sync.value = true;
  } catch (err) {
    message.error('执行 SQL 时发生错误');
    console.error('execute sql error ->', err);
  }
};

// 同步类目
const sync_category = async () => {
  try {
    const sync_res = await sync_align_result();
    console.log('sync_res ->', sync_res);
    message.success('同步类目成功');
  } catch (err) {
    message.error('同步类目时发生错误');
    console.error('sync category error ->', err);
  }
};

// 完成
const finish = () => {
  $router.push('/category');
};
</script>

<script>
import MonacoEditor from '@/components/commons/MonacoEditor.vue';
import { message, Button, Space, Upload } from 'ant-design-vue';
import {
  RocketOutlined,
  UploadOutlined,
  DownloadOutlined,
  FileSyncOutlined,
  CheckOutlined,
} from '@ant-design/icons-vue';

export default {
  name: 'SelSqlGeneration',
  components: {
    MonacoEditor,
    AButton: Button,
    ASpace: Space,
    AUpload: Upload,
    RocketOutlined,
    UploadOutlined,
    DownloadOutlined,
    FileSyncOutlined,
    CheckOutlined,
  },
};
</script>

<style lang="scss" scoped>
.editor_container {
  padding: 0px 100px;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .code-container {
    height: 100%;
    width: 52%;

    .code-header {
      flex-grow: 1;
      padding: 4px 4px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }

  .result-container {
    width: 45%;
    height: 100%;

    .result-header {
      flex-grow: 1;
      padding: 4px 4px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
